import store from '@/store'
import { uploadFile } from '@/api/common.js'
const baseurl = window.config.getAuthUrl().baseUrl
// 公用的上传方法
export function uploadFunc(file_lists) {
	console.log(file_lists)
	return new Promise((resolve, reject) => {
		if (!file_lists.length) {
			resolve(file_lists)
			return
		}
		const ulpad = (item, index) => {
			item.status = 'uploading'
			const formData = new FormData()
			formData.append('file', item.raw)
			formData.append('token', store.getters.token)

			uploadFile(formData).then(res => {
				item.status === 'success'
				const idx = item.index
				item.url = file_lists[idx].url = res.data.uri

				// 全部上传完后提交
				if (index === file_lists.length - 1) {
					resolve(file_lists)
				}
			}, err => {
				console.log(err)
				item.status = 'ready'
				reject('图片上传失败！')
			})

		}

		for (let i = 0; i < file_lists.length; i++) {
			const item = file_lists[i]
			if (!item.raw || item.status === 'uploading' || item.status === 'success') {
				if (item.status !== 'uploading' && i === file_lists.length - 1) {
					resolve(file_lists)
				}
				continue
			}
			ulpad(item, i)
		}

	})
}